<?php
namespace ms\components\behaviors;

use yii;
use yii\base\Behavior;
use yii\web\User;
use common\util\F;
use yii\db\Query;
use common\models\UserLog;
use common\models\BaseAdminSite;
use common\models\BaseSite;


class UserBehavior extends Behavior {
	
	public function events() {
		return [
			User::EVENT_AFTER_LOGIN => 'afterLogin',
			User::EVENT_BEFORE_LOGOUT => 'beforeLogout'
		];
	}
	
	/**
	 * 
	 * @Title: afterLogin
	 * @Description: 用户登录之后触发事件 
	 * @return: return_type
	 * @author: kai.gao
	 * @date: 2014-11-28 上午11:00:13
	 */
	public function afterLogin() {
		$user = $this->owner;
		$identity = $user->getIdentity();
		$identity->last_login_time = time();
		$identity->last_ip = F::IP();
		$identity->save();
		$roles = array_keys((new Query())->select('*')->indexBy('item_name')->from('{{%sys_auth_assignment}}')->where(['user_id' => $user->id])->all());
		$role = [1 => '客服', 2 => '供应商', 3 => '财务', 4 => '客务', 5 => '移动管理人员', 6 => '售后客服'];
		$role_id = isset(array_keys(array_intersect($role, $roles))[0]) ? array_keys(array_intersect($role, $roles))[0] : 0;
		f_s('role_id', $role_id); //保存用户角色信息
		$admin_user = $identity->attributes;
		unset($admin_user['password']); //删除session中的密码项
		f_s('admin_user', $admin_user);
		
		f_s('user_id', $identity->id);
		f_s('user_name', $identity->user_name);
		$this->insertLog('登录系统');
	} 
	
	public function beforeLogout() {
		$this->insertLog('退出系统');
	}
	
	private function insertLog($status) {
//		$user = $this->owner;
//		$identity = $user->getIdentity();
//		$attributes = [
//			'message' => $identity->user_name.':'.$status,
//			'ip' => F::IP(),
//			'site_id' => 1,
//			'server' => var_export($_SERVER, true),
//			'log_time' =>  date('Y-m-d H:i:s'),
//			'user_id' => $user->id,
//			'sys' => Yii::$app->id,
//		];
//		$log = new UserLog();
//		$log->attributes = $attributes;
//		$log->save();
	}
	
	/**
	 * @Title: getName
	 * @Description: 使用Yii::$app->user->name获取用户名 
	 * @return: string 登录用户名
	 * @author: kai.gao
	 * @date: 2014-11-28 上午11:00:32
	 */
	public function getName() {
		$user = $this->owner;
		$identity = $user->getIdentity();
		return $user->getIsGuest() ? null : $identity->name;  
	}	    
}